import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-jwt';
import type { StrategyOptions } from 'passport-jwt';
import { Injectable } from '@nestjs/common';

import { BusinessException } from 'src/common/exceptions/business.exception';
import { AdminService } from '../admin.service';
import { AdminEntity } from '../entities/admin.entity';
@Injectable()
export class JwtAdminStrategy extends PassportStrategy(Strategy, 'adminJwt') {
  // 这里的 Strategy 必须是 passport-jwt 包中的
  constructor(private readonly adminUserService: AdminService) {
    super({
      jwtFromRequest: (request) => {
        let token = null;
        if (request && request.headers['token']) {
          token = request.headers['token'];
        }
        return token;
      },
      secretOrKey: '加密Admin',
    } as StrategyOptions);
  }
  async validate(payload: AdminEntity) {
    const existUser = await this.adminUserService.findOne(payload.id);
    if (!existUser) BusinessException.throwForbidden();
    return existUser;
  }
}
